<?php
class Sqlite2Adapter extends SqliteAdapter
{
    protected static $openedConnections = array();

    public function Sqlite2Adapter($name)
    {
        parent::__construct($name);
        $this->driver = new SqliteDriver(AppConfig::GetInstance()->DIR_CONFIG.DS.$this->name);
        self::Add($this->name, $this);
    }

    public static function Get($name)
    {
        if (!self::IsExisted($name))
            new Sqlite2Adapter($name);
        return self::$openedConnections[$name];
    }

    protected static function Add($name, $conn)
    {
        self::$openedConnections[$name] = $conn;
    }

    protected static function Remove($name)
    {
        unset(self::$openedConnections[$name]);
    }

    protected static function IsExisted($name)
    {
        return isset(self::$openedConnections[$name]);
    }

    public static function CloseAll()
    {
        foreach (self::$openedConnections as $conn)
        {
            $conn->Close();
        }
    }

    public function GetInsertId()
    {
        return $this->driver->lastInsertRowid();
    }

    public function GetAffectedRows()
    {
        return $this->driver->changes();
    }

    protected function FetchResult($result)
    {
        $output = array();
        while ($row = sqlite_fetch_array($result))
        {
            foreach ($row as $key => $value)
            {
                $tmp = explode('.', $key);
                $newkey = count($tmp) > 1 ? $tmp[1] : $key;
                $newrow[$newkey] = $value;
            }
            $output[] = $newrow;
        }
        return $output;
    }

    public function ExecuteMulti($sql)
    {
        return $this->driver->queryExec($sql);
    }

    public function EscapeString($string)
    {
        return sqlite_escape_string($string);
    }

    public function GetLastError()
    {
        return $this->driver->lastError();
    }

    public function GetErrorMessage()
    {
        return sqlite_error_string($this->GetLastError());
    }
}
?>
